import redis
import datetime
import json
import time

# redis 的生命周期
day = 7


# 数据共享类，方便存放数据
class SharedData:
    # pool = redis.ConnectionPool(host='localhost', port=6379, decode_responses=True, db=9)
    pool = redis.ConnectionPool(host='172.16.200.251', port=6379, decode_responses=True, db=9)
    r = redis.StrictRedis(connection_pool=pool)

    @classmethod
    def GetToday(cls, stat):
        key = datetime.datetime.now().strftime('%F')
        key += '_%s' % stat
        return cls.GetList(key)

    @classmethod
    def PutToday(cls, stat, val):
        key = datetime.datetime.now().strftime('%F')
        key += '_%s' % stat
        cls.PushVal(key, val)

    @classmethod
    def GetYesterday(cls, stat):
        key = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%F')
        key += '_%s' % stat
        return cls.GetList(key)

    @classmethod
    def PutYesterday(cls, stat, val):
        key = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%F')
        key += '_%s' % stat
        cls.PushVal(key, val)

    @classmethod
    def PushVal(cls, key, val):
        values = json.dumps(val)
        cls.r.rpush(key, values)
        if cls.GetTTL(key) == -1:
            cls.SetTTL(key)

    @classmethod
    def GetList(cls, key):
        r_result = cls.r.lrange(key, 0, -1)
        return [json.loads(x) for x in r_result]

    @classmethod
    def GetTTL(cls, key):
        return cls.r.ttl(key)

    @classmethod
    def SetTTL(cls, key):
        date_format = '%Y-%m-%d %H:%M:%S'
        dt = (datetime.datetime.now().date() + datetime.timedelta(days=day)).strftime(date_format)
        date_int = int(time.mktime(time.strptime(dt, date_format)))
        cls.r.expireat(key, date_int)

    @classmethod
    def PutLog(cls, val):
        key = 'ServeLog'
        cls.PushVal(key, val)

    @classmethod
    def GetLog(cls):
        key = 'ServeLog'
        res = cls.r.lpop(key)
        return json.loads(res)

    @classmethod
    def GetSuccess(cls, stat):
        yesterday = cls.GetYesterday(stat)
        today = cls.GetToday(stat)
        return yesterday + today

    @classmethod
    def GetLogLen(cls):
        return cls.r.llen('ServeLog')


class Distribution:
    key_name = "Distribution_L"

    @classmethod
    def addLog(cls, file, server):
        content = {"File": file, "Server": server, "Time": datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
        SharedData.r.rpush(cls.key_name, json.dumps(content))

    @classmethod
    def getLog(cls):
        content = SharedData.r.lpop(cls.key_name)
        return json.loads(content)

    @classmethod
    def GetLogLen(cls):
        return SharedData.r.llen(cls.key_name)


class ImosChange:
    key_name = "ImosTime"
    rm_name = 'ImosWire'
    md5 = "LastTime"

    @classmethod
    def setServerTime(cls, server, time_):
        SharedData.r.hset(cls.key_name, server, time_)

    @classmethod
    def getServerTime(cls, server):
        return SharedData.r.hget(cls.key_name, server)

    @classmethod
    def setLast(cls, server, key: str):
        SharedData.r.hset(cls.md5, server, key)

    @classmethod
    def getLast(cls, server):
        return SharedData.r.hget(cls.md5, server)

    @classmethod
    def setMeTime(cls, server, time_):
        SharedData.r.hset(cls.rm_name, server, time_)

    @classmethod
    def getMeTime(cls, server):
        return SharedData.r.hget(cls.rm_name, server)


class NoSqlDataGet:

    # last是上一个进行对比的，me是自己的
    @staticmethod
    def GetNeed(last, me):
        today_data = SharedData.GetToday(last)
        td_j = [json.dumps(x) for x in today_data]
        success_data = SharedData.GetSuccess(me)
        su_j = [json.dumps(x) for x in success_data]
        difference = list(set(td_j) - set(su_j))
        return [json.loads(x) for x in difference]

    @staticmethod
    def AppendSuccess(stat, success_data):
        SharedData.PutToday(stat, success_data)

    @staticmethod
    def GetTodayLog():
        td_s = SharedData.GetToday('L')
        res = NoSqlDataGet.getDay(today=True)
        res = [json.dumps(x) for x in res]
        td_s = [json.dumps(x) for x in td_s]
        difference = list(set(res) - set(td_s))
        return [json.loads(x) for x in difference]

    @staticmethod
    def GetYesterdayLog():
        td_s = SharedData.GetYesterday('L')
        res = NoSqlDataGet.getDay()
        res = [json.dumps(x) for x in res]
        td_s = [json.dumps(x) for x in td_s]
        difference = list(set(res) - set(td_s))
        return [json.loads(x) for x in difference]

    @staticmethod
    def getDay(today=False):
        if today:
            get_stat = SharedData.GetToday
            res = SharedData.GetToday("F")
            NoSqlDataGet.changeStat(res, 1)
        else:
            get_stat = SharedData.GetYesterday
            res = NoSqlDataGet.getSuccess()
        for td in [0, 2]:
            temp_list = get_stat(td)
            NoSqlDataGet.changeStat(temp_list, td)
            res += temp_list
        return res

    @staticmethod
    def changeStat(change_list: list, stat: int):
        for x in change_list:
            del x['Server']
            x['Status'] = stat

    @staticmethod
    def getSuccess():
        success_file = SharedData.GetYesterday('F') + SharedData.GetToday('F')
        success_log = SharedData.GetYesterday(1)
        success_file = [json.dumps(x) for x in success_file]
        success_log = [json.dumps(x) for x in success_log]
        res = list(set(success_file) & set(success_log))
        res = [json.loads(x) for x in res]
        NoSqlDataGet.changeStat(res, 1)
        return res

    @staticmethod
    def SetTodayLog(infos):
        for td in infos:
            SharedData.PutToday('L', td)

    @staticmethod
    def SetYesterdayLog(infos):
        for td in infos:
            SharedData.PutYesterday('L', td)


class Heart:

    # 服务端让自己成为的状态
    @staticmethod
    def getMeHeart(class_name):
        key = str(class_name) + '_H'
        return bool(int(SharedData.r.get(key)))

    @staticmethod
    def setMeHeart(class_name, stat: bool):
        key = str(class_name) + '_H'
        return SharedData.r.set(key, int(stat))

    # 自己的转态        self.__class__.__name__
    @staticmethod
    def getMeStat(class_name):
        key = str(class_name) + '_M'
        return bool(int(SharedData.r.get(key)))

    @staticmethod
    def setMeStat(class_name, stat: bool):
        key = str(class_name) + '_M'
        return SharedData.r.set(key, int(stat))

    # 自己的进程号        self.__class__.__name__
    @staticmethod
    def getPid(class_name):
        t_name = 'ServicesPID'
        key = str(class_name)
        return int(SharedData.r.hget(t_name, key))

    @staticmethod
    def setPid(class_name, pid: int):
        t_name = 'ServicesPID'
        key = str(class_name)
        return SharedData.r.hset(t_name, key, pid)


class SanWeiJiaConvert:
    field = 'SWJ_{}_S'

    @classmethod
    def putData(cls, order_no):
        yesterday = SharedData.GetYesterday('F')
        if order_no in yesterday:
            field = cls.field.format(datetime.datetime.now().strftime('%F'))
        else:
            field = cls.field.format((datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%F'))
        SharedData.PushVal(field, order_no)

    @classmethod
    def getData(cls):
        success_file = SharedData.GetYesterday('F') + SharedData.GetToday('F')
        today = cls.field.format(datetime.datetime.now().strftime('%F'))
        yesterday = cls.field.format((datetime.datetime.now() - datetime.timedelta(days=1)).strftime('%F'))
        success_swj = SharedData.GetList(today) + SharedData.GetList(yesterday)
        success_file = [json.dumps(x) for x in success_file]
        success_swj = [json.dumps(x) for x in success_swj]
        res = list(set(success_file) - set(success_swj))
        return [json.loads(x) for x in res]


if __name__ == '__main__':
    # SharedData.PutToday(0, {"OrderNO": "AJLSY022005108YG-05-04", "CreateDate": "2020/5/26 15:21:02"})
    # result = SharedData.GetToday(1)
    # print(SharedData.SetTTL(datetime.datetime.now().strftime('%F_1')))
    # Heart.setMeHeart("tt", False)
    # a = Heart.getMeHeart("tt")
    a = ImosChange.getTime()
    print(a)
